<template>
  <!-- 数据权限推窗 -->
  <BaseDrawer
    width="540px"
    :title="t('routes.role.assignDataPermissions')"
    placement="right"
    v-model:visible="dataScopeOpen"
    :maskClosable="false"
    @close="handleClose"
  >
    <template #default>
      <a-form
        v-if="dataScopeOpen"
        ref="formScopeRef"
        :model="formScopeState"
        :rules="scopeRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-row>
          <a-col :span="24">
            <a-form-item :label="t('routes.role.roleName')" name="roleName">
              <a-input
                :disabled="true"
                v-model:value="formScopeState.roleName"
                :placeholder="t('routes.role.roleNamePlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="t('routes.role.roleKey')" name="roleKey">
              <a-input
                :disabled="true"
                v-model:value="formScopeState.roleKey"
                :placeholder="t('routes.role.roleKeyPlaceholder')"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :label="t('routes.role.dataScope')" name="dataScope">
              <a-select
                v-model:value="formScopeState.dataScope"
                :placeholder="t('routes.role.dataScopePlaceholder')"
              >
                <a-select-option
                  v-for="item in dataScopeOptions"
                  :key="item.value"
                >
                  {{ item.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </template>
    <template #footer>
      <a-button type="primary" class="mr-3" @click="handleScopeSubmit">
        {{ t("common.okText") }}
      </a-button>
      <a-button @click="handleClose">{{ t("common.cancelText") }}</a-button>
    </template>
  </BaseDrawer>
</template>
<script lang="ts">
import { defineComponent, reactive, ref, nextTick } from "vue";
import {
  Row,
  Col,
  Form,
  FormItem,
  Input,
  Select,
  SelectOption,
} from "ant-design-vue";
import BaseDrawer from "@/components/BaseDrawer/index.vue";
import { getRoleById, updateRole } from "@/api/admin/system/role";
import { message as Message } from "ant-design-vue";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { useI18n } from "@/hooks/useI18n";

const { t } = useI18n();

interface FormScopeState {
  id: undefined | number;
  roleName: undefined | string;
  roleKey: undefined | string;
  roleSort: undefined | number | string;
  status: undefined | string;
  menuIds: undefined | number[];
  remark: undefined | string;
  dataScope: undefined;
}

export default defineComponent({
  components: {
    "a-row": Row,
    "a-col": Col,
    "a-form": Form,
    "a-form-item": FormItem,
    "a-input": Input,
    "a-select": Select,
    "a-select-option": SelectOption,
    BaseDrawer,
  },
  emits: ["finished"],
  setup(props, { expose, emit }) {
    // 数据范围选项
    const dataScopeOptions = reactive([
      {
        value: "1",
        label: t("routes.role.CurrentAndBelow"),
      },
      {
        value: "2",
        label: t("routes.role.current"),
      },
      {
        value: "3",
        label: t("routes.role.myself"),
      },
    ]);
    const formScopeRef = ref();
    const dataScopeOpen = ref(false);
    const scopeRules = {
      dataScope: [
        {
          required: true,
          message: t("routes.role.menuIdsIsEmpty"),
          trigger: "blur",
        },
      ],
    };
    const formScopeState: FormScopeState = reactive({
      id: undefined,
      roleName: undefined || "",
      roleKey: undefined || "",
      roleSort: undefined,
      status: undefined,
      menuIds: undefined,
      remark: undefined,
      dataScope: undefined,
    });
    // 隐藏推窗
    const handleClose = (cb?: () => void) => {
      dataScopeOpen.value = false;
      cb && typeof cb === "function" && cb();
    };
    // 显示推窗
    const handleShow = (row) => {
      getRoleById(row.id).then((res) => {
        dataScopeOpen.value = true;
        nextTick(() => {
          Object.keys(formScopeState).forEach((key) => {
            formScopeState[key] = res.data[key];
          });
          formScopeState.menuIds = res.data.menus.map((list) => list.id);
        });
      });
    };

    // 提交表单
    const handleScopeSubmit = () => {
      formScopeRef.value
        .validate()
        .then(() => {
          console.log("ok");
          updateRole(formScopeState).then((res) => {
            handleClose(() => {
              Message.success(res.message);
              emit("finished");
            });
          });
        })
        .catch((error: ValidateErrorEntity) => {
          console.log("error", error);
        });
    };

    expose({
      handleShow,
    });

    return {
      t,
      labelCol: { span: 4 },
      wrapperCol: { span: 20 },
      dataScopeOptions,
      formScopeRef,
      dataScopeOpen,
      formScopeState,
      scopeRules,
      handleClose,
      handleScopeSubmit,
    };
  },
});
</script>
